package com.example.demo0710;

import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import android.widget.RelativeLayout.LayoutParams;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class SeeKBarActivity extends AppCompatActivity {

    private TextView mTvNum;
    private SeekBar mSeekBar;
    private double width, fDensity;
    private int numbers = 0;
    private DisplayMetrics displaysMetrics = new DisplayMetrics();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seek_bar);
        initView();
        initSeekBarProgress();
    }

    private void initSeekBarProgress() {
        mSeekBar.setProgress(numbers);
        mSeekBar.setOnSeekBarChangeListener(mSeekChange);
    }

    private OnSeekBarChangeListener mSeekChange = new OnSeekBarChangeListener() {
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            numbers = progress;
            LayoutParams paramsStrength = new LayoutParams(
                    LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            paramsStrength.leftMargin = (int) (progress * fDensity);
            Log.i("progress", "leftMargin" + paramsStrength.leftMargin);
            mTvNum.setLayoutParams(paramsStrength);
            mTvNum.setText(numbers + "%");

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }


    };

    private void initView() {
        mTvNum = (TextView) findViewById(R.id.tv_num);
        mSeekBar = (SeekBar) findViewById(R.id.seekBar);
        displaysMetrics = getResources().getDisplayMetrics();
        width = displaysMetrics.widthPixels;
        fDensity = (width - dip2px(this, 75)) / 100;
        Log.i("progress", "width:" + width);
        Log.i("progress", "fDensity" + fDensity);
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}